package cn.detu.baking.controller;

import cn.detu.baking.mapper.UserMapper;
import cn.detu.baking.pojo.dto.UserLoginDTO;
import cn.detu.baking.pojo.dto.UserRegDTO;
import cn.detu.baking.pojo.dto.UserUpdateDTO;
import cn.detu.baking.pojo.entity.User;
import cn.detu.baking.pojo.vo.UserAdminVO;
import cn.detu.baking.pojo.vo.UserVO;
import cn.detu.baking.response.ResultVO;
import cn.detu.baking.response.StatusCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * Date:2024/3/23
 * Author：
 * Description:
 */
@RestController
@RequestMapping("/v1/users/")
public class userController {
    @Autowired
    UserMapper mapper;

    @Autowired
    PasswordEncoder passwordEncoder;
    @RequestMapping("reg")
    public ResultVO reg(@RequestBody UserRegDTO userRegDTO){
        UserVO userVO = mapper.selectByUserName(userRegDTO.getUserName());
        if (userVO!=null){//代表用户名已存在
            return new ResultVO(StatusCode.USERNAME_ALREADY_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreateTime(new Date());
        user.setIsAdmin(0);//默认不是管理员
        user.setImgUrl("/imgs/icon.png");
        //让密码加密
//        user.setPassword(passwordEncoder.encode(user.getPassword()));

        mapper.insert(user);
        return ResultVO.ok();
    }


    @Autowired
    AuthenticationManager manager;
    @RequestMapping("login")
    public ResultVO login(@RequestBody UserLoginDTO userLoginDTO){
        Authentication result = manager.authenticate(new UsernamePasswordAuthenticationToken(
                userLoginDTO.getUserName(), userLoginDTO.getPassword()));
        //将认证结果保存到Security上下文中   让Security框架记住登录状态
        SecurityContextHolder.getContext().setAuthentication(result);
        //代码执行到这里时代表登录成功!如果登录失败Security框架会抛出异常
//        return ResultVO.ok();
        System.out.println(result.getPrincipal());
        return new ResultVO(StatusCode.SUCCESS,result.getPrincipal());//登录成功

    }

    @RequestMapping("logout")
    public void logout(){
        //从Security框架中删除认证数据
        SecurityContextHolder.clearContext();
    }

    @RequestMapping("update")
    public ResultVO update(@RequestBody UserUpdateDTO userUpdateDTO){
        User user = new User();
        BeanUtils.copyProperties(userUpdateDTO,user);
        mapper.update(user);

        return ResultVO.ok();

    }

    @PreAuthorize("hasAuthority('ADMIN')")//设置有管理员权限才能访问
    @RequestMapping("")
    public ResultVO list(){
        List<UserAdminVO> list = mapper.select();
        return ResultVO.ok(list);
    }

    @PreAuthorize("hasAuthority('ADMIN')")//设置有管理员权限才能访问
    @RequestMapping("/{id}/{isAdmin}/change")
    public ResultVO change(@PathVariable Long id,@PathVariable Integer isAdmin){
        User user = new User();
        user.setId(id);
        user.setIsAdmin(isAdmin);
        mapper.update(user);
        return ResultVO.ok();
    }

    @PreAuthorize("hasAuthority('ADMIN')")//设置有管理员权限才能访问
    @RequestMapping("/{id}/delete")
    public ResultVO delete(@PathVariable Long id){
        mapper.deleteById(id);
        return ResultVO.ok();
    }



}
